package com.liu.queue.handler;

import com.liu.common.Constants;
import com.liu.message.impl.ResponseMessage;
import com.liu.queue.agreement.Agreement;
import com.liu.queue.message.MessageTypeEnum;
import com.liu.queue.message.impl.PushOrdinaryReqeustMessage;
import com.liu.queue.storage.StorageProvider;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @param
 * @BelongsProject: QueueDemo2
 * @BelongsPackage: com.liu.queue.handlerPush
 * @author: L
 * @Date: 2023/10/16 9:31
 * @return
 */
@Slf4j
public class PushOrdinaryRequestHandler extends SimpleChannelInboundHandler<PushOrdinaryReqeustMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PushOrdinaryReqeustMessage msg) throws Exception {
        log.info("推送消息");
        // 寻找对应的存储处理器   根据消息类型来
        ResponseMessage responseMessage = StorageProvider.handlerPush(msg);
        Agreement agreement = new Agreement(Constants.MAGIC_NUMBER,
                Constants.VERSION,
                MessageTypeEnum.RESPONSE,
                msg.getSerializationType(),
                msg.getTopic(),
                msg.getMessageID());
        agreement.setBody(responseMessage);
        // 响应写回给客户端,并断开这个连接
        ctx.writeAndFlush(agreement).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
